import { core, getImage, RenderableBehaviour } from "./gameengine";
import { getPlatform } from "./platform";

export class AnimationRenderer extends RenderableBehaviour {

    private image:HTMLImageElement;
    private config:any;
    private duringTime:number = 0;
    private currentFrame:number = 0;
    public isIdle=true;

    public currentOffset=0;
    public mod=4;

    protected onStart() {
        this.displayObject.renderNode = this;

         getPlatform().loadText("assets/json/anim.json",(text)=>{
            this.config = JSON.parse(text);
            core.loadImage("assets/picture/anim.png");
            this.image =  getImage('assets/picture/anim.png')
        })


    }    
    protected onUpdate(advancedTime: number) {
        if(this.isIdle){
            this.mod=1;
        }else {
            this.mod=4;
        }
      
        if (!this.config){
            return;
        }
        this.duringTime += advancedTime;
        this.currentFrame = (Math.floor(this.duringTime / 32 /4)) % this.mod+this.currentOffset;
    }

    onRender(context:CanvasRenderingContext2D){
        if (this.config){
            const url = this.currentFrame + 1 + ".png";
            const rect = this.config[url];
            // console.log(url);
            context.drawImage(this.image,rect.x,rect.y,rect.width,rect.height,rect.offsetX,rect.offsetY,rect.width,rect.height);
        }
    }

    public getRenderArea() {
        return { x: 0, y: 0, width: 45, height: 64 }
    }
}